<template>
    <div class="duty-schedule">

        <div class="header-right">
            <el-button type="primary" size="small" @click="addDuty">
                <i class="el-icon-plus"></i> 添加值班
            </el-button>
            <div class="view-toggle">
                <el-radio-group v-model="viewMode" size="small">
                    <el-radio-button label="calendar">
                        <i class="el-icon-date"></i> 日历视图
                    </el-radio-button>
                    <el-radio-button label="list">
                        <i class="el-icon-menu"></i> 列表视图
                    </el-radio-button>
                </el-radio-group>
            </div>

        </div>


        <!-- 自定义日历视图 -->
        <div v-if="viewMode === 'calendar'" class="calendar-view">
            <div class="calendar-header">
                <div class="calendar-nav">
                    <el-button-group>
                        <el-button size="small" @click="previousMonth" icon="el-icon-arrow-left"></el-button>
                        <el-button size="small" @click="nextMonth" icon="el-icon-arrow-right"></el-button>
                    </el-button-group>
                    <h3 class="current-month">{{ currentMonthText }}</h3>
                </div>

                <div class="calendar-legend">
                    <div class="legend-item">
                        <span class="legend-color day"></span>
                        <span>白班</span>
                    </div>
                    <div class="legend-item">
                        <span class="legend-color night"></span>
                        <span>夜班</span>
                    </div>
                    <div class="legend-item">
                        <span class="legend-color rest"></span>
                        <span>休息</span>
                    </div>
                </div>
            </div>

            <el-calendar v-model="currentDate" class="duty-calendar">
                <template slot="dateCell" slot-scope="{data}">
                    <div class="calendar-cell">
                        <div class="day-header">
                            <span class="date-number">{{ data.day.split('-').slice(2).join('') }}</span>
                            <div class="duty-names">
                                <div v-for="duty in getDutiesByDate(data.day)" :key="duty.id"
                                    @click.stop="editDuty(duty)">
                                    <el-popover placement="top-start" title="" width="200" trigger="hover"
                                        :content="`${duty.nickName} - ${duty.startTime} - ${duty.endTime}`">
                                        <el-tag slot="reference" :type="getColor(duty.type)">
                                            <i style="font-size: 14px;margin-right: 5px;"
                                                :class="getTypeIcon(duty.type)"></i>{{ duty.nickName }}</el-tag>
                                    </el-popover>

                                </div>
                            </div>

                            <el-button size="mini" type="text" icon="el-icon-plus"
                                @click.stop="addDutyForDate(data.day)" v-show="isExpired(data)"
                                class="add-duty-btn"></el-button>
                        </div>
                    </div>
                </template>
            </el-calendar>
        </div>

        <!-- 列表视图 -->
        <div v-else class="list-view">
            <div class="list-header">
                <div class="list-controls">
                    <el-select v-model="filterType" placeholder="筛选值班类型" size="medium" style="width: 150px;">
                        <el-option label="全部" value=""></el-option>
                        <el-option label="白班" value="day"></el-option>
                        <el-option label="夜班" value="night"></el-option>
                        <el-option label="休息" value="rest"></el-option>
                    </el-select>
                    <el-date-picker v-model="filterDate" type="month" placeholder="选择月份" size="medium"
                        style="width: 150px; margin-left: 10px;"></el-date-picker>
                </div>
                <div class="list-stats">
                    <el-tag type="success">{{ filteredDutyList.length }} 条记录</el-tag>
                </div>
            </div>

            <el-table :data="filteredDutyList" style="width: 100%" height="100%">
                <el-table-column prop="date" label="日期" align="center" width="120">
                    <template slot-scope="scope">
                        <div class="date-cell">
                            <div class="date-main">{{ formatDate(scope.row.date) }}</div>
                            <div class="date-weekday">{{ getWeekday(scope.row.date) }}</div>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column prop="name" label="值班人员" align="center" width="120">
                    <template slot-scope="scope">
                        <div class="name-cell">
                            <i class="el-icon-user"></i>
                            {{ scope.row.nickName }}
                        </div>
                    </template>
                </el-table-column>
                <el-table-column prop="type" label="值班类型" align="center" width="100">
                    <template slot-scope="scope">
                        <el-tag :type="getTagType(scope.row.type)" size="medium">
                            <i :class="getTypeIcon(scope.row.type)"></i>
                            {{ getTypeText(scope.row.type) }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="startTime" label="开始时间" align="center" width="120">
                    <template slot-scope="scope">
                        <i class="el-icon-time"></i>
                        {{ scope.row.startTime }}
                    </template>
                </el-table-column>
                <el-table-column prop="endTime" label="结束时间" align="center" width="120">
                    <template slot-scope="scope">
                        <i class="el-icon-time"></i>
                        {{ scope.row.endTime }}
                    </template>
                </el-table-column>
                <el-table-column prop="notes"  align="center"label="备注">
                    <template slot-scope="scope">
                        <span v-if="scope.row.notes">{{ scope.row.notes }}</span>
                        <span v-else class="no-notes">无备注</span>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="180" align="center" fixed="right">
                    <template slot-scope="scope">
                        <el-button size="mini" type="text" @click="editDuty(scope.row)">
                            <i class="el-icon-edit"></i> 编辑
                        </el-button>
                        <el-button size="mini" type="text" @click="deleteDuty(scope.row)">
                            <i class="el-icon-delete"></i> 删除
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>

        <!-- 添加/编辑值班对话框 -->
        <el-dialog :title="dialogTitle" :visible.sync="showAddDialog" width="600px" :close-on-click-modal="false"
            @close="closeDialog" class="duty-dialog">
            <el-form :model="dutyForm" :rules="rules" ref="dutyForm" label-width="100px">
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="值班日期" prop="date">
                            <el-date-picker v-model="dutyForm.date" type="date" format="yyyy-MM-dd"
                                value-format="yyyy-MM-dd" placeholder="选择日期" style="width: 100%;">
                            </el-date-picker>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="值班人员" prop="userIds">
                            <UserSelect :disabled="isDisabled" v-model="dutyForm.userIds" :multiple="true"
                                placeholder="请选择值班人员" />
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="值班类型" prop="type">
                            <el-select v-model="dutyForm.type" placeholder="请选择值班类型" :disabled="isDisabled"
                                style="width: 100%;">
                                <el-option label="白班" value="day">
                                    <i class="el-icon-sunny"></i> 白班
                                </el-option>
                                <el-option label="夜班" value="night">
                                    <i class="el-icon-moon"></i> 夜班
                                </el-option>
                                <el-option label="休息" value="rest">
                                    <i class="el-icon-house"></i> 休息
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="开始时间" prop="startTime">
                            <el-date-picker v-model="dutyForm.startTime" placeholder="选择开始时间" format="yyyy-MM-dd HH:mm"
                                type="datetime" :disabled="isDisabled" value-format="yyyy-MM-dd HH:mm"
                                style="width: 100%;">
                            </el-date-picker>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="结束时间" prop="endTime">
                            <el-date-picker v-model="dutyForm.endTime" placeholder="选择结束时间" format="yyyy-MM-dd HH:mm"
                                type="datetime" :disabled="isDisabled" value-format="yyyy-MM-dd HH:mm"
                                style="width: 100%;">
                            </el-date-picker>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="状态">
                            <el-tag :type="getStatusType()" size="medium">
                                {{ getStatusText() }}
                            </el-tag>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-form-item label="备注">
                    <el-input type="textarea" :disabled="isDisabled" v-model="dutyForm.notes" placeholder="请输入备注信息"
                        :rows="3"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer" v-show="!isDisabled">
                <el-button @click="showAddDialog = false">取消</el-button>
                <el-button type="primary" @click="saveDuty" :loading="saving">
                    <i class="el-icon-check"></i> 确定
                </el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import UserSelect from '@/components/Select/UserSelect'
import moment from 'moment';
export default {
    name: 'DutySchedule',
    components: { UserSelect },
    data() {
        return {
            viewMode: 'calendar',
            currentDate: new Date(),
            showAddDialog: false,
            filterType: '',
            filterDate: null,
            editingDuty: null,
            saving: false,

            dutyForm: {
                date: '',
                userIds: [],
                type: '',
                startTime: '',
                endTime: '',
                notes: ''
            },
            rules: {
                date: [{ required: true, message: '请选择值班日期', trigger: 'change' }],
                name: [{ required: true, message: '请输入值班人员姓名', trigger: 'blur' }],
                type: [{ required: true, message: '请选择值班类型', trigger: 'change' }],
                startTime: [{ required: true, message: '请选择开始时间', trigger: 'change' }],
                endTime: [{ required: true, message: '请选择结束时间', trigger: 'change' }]
            },
            dutyList: []
        }
    },
    computed: {
        currentMonthText() {
            const year = this.currentDate.getFullYear()
            const month = this.currentDate.getMonth() + 1
            return `${year}年${month}月`
        },

        filteredDutyList() {
            let filtered = this.dutyList

            if (this.filterType) {
                filtered = filtered.filter(duty => duty.type === this.filterType)
            }

            if (this.filterDate) {
                const filterYear = this.filterDate.getFullYear()
                const filterMonth = this.filterDate.getMonth()
                filtered = filtered.filter(duty => {
                    const dutyDate = new Date(duty.date)
                    return dutyDate.getFullYear() === filterYear && dutyDate.getMonth() === filterMonth
                })
            }

            return filtered.sort((a, b) => new Date(a.date) - new Date(b.date))
        },
        dialogTitle() {
            return this.editingDuty ? '编辑值班安排' : '添加值班安排'
        },
        isDisabled() {
            if (moment().add(-1, 'day').isAfter(moment(this.dutyForm.date))) {
                return true
            } else {
                return false
            }
        },
    },
    created() {
        this.getList();
    },
    methods: {
        getList() {
            this.loading = true;
            this.$request({
                url: 'baseApi/cus_duty/getList',
                method: 'get',
                params: {
                    date: new Date()
                }
            }).then((res) => {
                this.dutyList = res.data;
            })
        },
        previousMonth() {
            const newDate = new Date(this.currentDate)
            newDate.setMonth(newDate.getMonth() - 1)
            this.currentDate = newDate
        },
        nextMonth() {
            const newDate = new Date(this.currentDate)
            newDate.setMonth(newDate.getMonth() + 1)
            this.currentDate = newDate
        },
        addDutyForDate(dateString) {
            this.editingDuty = null
            this.dutyForm = {
                date: new Date(dateString),
                name: '',
                type: '',
                startTime: '',
                endTime: '',
                notes: ''
            }
            this.showAddDialog = true
        },

        getDutiesByDate(date) {
            return this.dutyList.filter(duty => duty.date === date)
        },
        getTagType(type) {
            const typeMap = {
                day: 'success',
                night: 'warning',
                rest: 'info'
            }
            return typeMap[type] || 'info'
        },
        getTypeText(type) {
            const typeMap = {
                day: '白班',
                night: '夜班',
                rest: '休息'
            }
            return typeMap[type] || type
        },
        getTypeIcon(type) {
            const iconMap = {
                day: 'el-icon-sunny',
                night: 'el-icon-moon',
                rest: 'el-icon-dish-1'
            }
            return iconMap[type] || 'el-icon-time'
        },
        getStatusType() {
            if (!this.dutyForm.date) return 'info'
            const today = new Date()
            const dutyDate = new Date(this.dutyForm.date)
            if (this.isSameDate(dutyDate, today)) return 'warning'
            if (dutyDate < today) return 'danger'
            return 'success'
        },
        getStatusText() {
            if (!this.dutyForm.date) return '未设置'
            const today = new Date()
            const dutyDate = new Date(this.dutyForm.date)
            if (this.isSameDate(dutyDate, today)) return '今日值班'
            if (dutyDate < today) return '已过期'
            return '即将值班'
        },
        formatDate(date) {
            const d = new Date(date)
            return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`
        },
        getWeekday(date) {
            const weekdays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']
            const d = new Date(date)
            return weekdays[d.getDay()]
        },
        isSameDate(date1, date2) {
            return date1.getFullYear() === date2.getFullYear() &&
                date1.getMonth() === date2.getMonth() &&
                date1.getDate() === date2.getDate()
        },
        addDuty() {
            this.showAddDialog = true
        },
        editDuty(duty) {
            this.editingDuty = duty
            let dutyList = this.dutyList
            let dutys = dutyList.filter(item => moment(item.date).isSame(duty.date)
                && moment(item.startTime).isSame(duty.startTime) && moment(item.endTime).isSame(duty.endTime)
            )
            const userIds = dutys.map(item => item.userId)
            const ids = dutys.map(item => item.id)
            this.dutyForm = {
                ...duty,
                date: new Date(duty.date),
                ids:ids,
                userIds: userIds
            }
            this.showAddDialog = true

        },
        getColor(type) {
            if (type == 'day') {
                return 'success'
            } else if (type == 'night') {
                return 'warning'
            } else {
                return 'info'
            }
        },
        isExpired(data) {
            if (moment().add(-1, 'day').isBefore(moment(data.day))) {
                return true
            } else {
                return false
            }
        },
        deleteDuty(duty) {
            this.$confirm('确定要删除这条值班记录吗？', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.$request({
                    url: '/baseApi/cus_duty/delete',
                    method: 'get',
                    params: {
                        id: duty.id
                    }
                }).then((res) => {
                    if (res.code === 200) {
                        this.$message({
                            message: '操作成功',
                            type: 'success'
                        });
                        this.getList()
                    }
                })
            }).catch(() => { })
        },
        saveDuty() {
            this.$refs.dutyForm.validate((valid) => {
                if (valid) {
                    this.saving = true
                    let url = ''
                    if (this.editingDuty) {
                        url = 'baseApi/cus_duty/update'
                    } else {
                        url = 'baseApi/cus_duty/insert'
                    }
                    this.$request({
                        url: url,
                        method: 'post',
                        data: this.dutyForm
                    }).then((res) => {
                        if (res.code === 200) {
                            this.$message({
                                message: '操作成功',
                                type: 'success'
                            });
                            this.showAddDialog = false
                            this.resetForm()
                            this.saving = false
                            this.getList()
                        }
                    })


                }
            })
        },
        resetForm() {
            this.editingDuty = null
            this.dutyForm = {
                date: '',
                name: '',
                type: '',
                startTime: '',
                endTime: '',
                notes: ''
            }
            this.$refs.dutyForm && this.$refs.dutyForm.resetFields()
        },
        closeDialog() {
            this.resetForm()
        },
    }
}
</script>

<style scoped>
.duty-schedule {
    height: 100%;
    overflow: hidden;
}


.header-right {
    display: flex;
    align-items: center;
    justify-content: flex-end;
    margin-bottom: 5px;
    gap: 20px;
}

.calendar-view {
    box-sizing: border-box;
    background: white;
    padding: 20px;
}

.calendar-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    padding-bottom: 20px;
    border-bottom: 1px solid #ebeef5;
}

.calendar-nav {
    display: flex;
    align-items: center;
    gap: 15px;
}

.current-month {
    margin: 0;
    font-size: 20px;
    font-weight: 600;
    color: #303133;
}

.calendar-legend {
    display: flex;
    gap: 20px;
}

.legend-item {
    display: flex;
    align-items: center;
    gap: 8px;
    font-size: 14px;
    color: #606266;
}

.legend-color {
    width: 16px;
    height: 16px;
    border-radius: 4px;
}

.legend-color.day {
    background-color: #67c23a;
}

.legend-color.night {
    background-color: #e6a23c;
}

.legend-color.rest {
    background-color: #909399;
}

.duty-calendar {
    border: 1px solid #ebeef5;
    border-radius: 8px;
    overflow: hidden;
}

.duty-calendar .el-calendar__header {
    padding: 20px;
    background: #fafafa;
    border-bottom: 1px solid #ebeef5;
}

.duty-calendar .el-calendar__body {
    padding: 0;
}

.duty-calendar .el-calendar-table {
    border: none;
    table-layout: fixed;
    width: 100%;
}

.duty-calendar .el-calendar-table th {
    background: #fafafa;
    border: none;
    padding: 12px;
    font-weight: 600;
    color: #606266;
    font-size: 14px;
    width: 14.2857%;
    box-sizing: border-box;
}

.duty-calendar .el-calendar-table td {
    border: 1px solid #ebeef5;
    padding: 0;
    height: 120px;
    vertical-align: top;
    position: relative;
    overflow: hidden;
    box-sizing: border-box;
}

.duty-calendar .el-calendar-table td.next {
    background-color: #fafafa;
    color: #c0c4cc;
}

.duty-calendar .el-calendar-table td.prev {
    background-color: #fafafa;
    color: #c0c4cc;
}

.duty-calendar .el-calendar-table td.current {
    background-color: #f0f9ff;
}

.duty-calendar .el-calendar-table td.today {
    background-color: #ecf5ff;
    border: 2px solid #409eff;
}

.calendar-cell {
    height: 100%;
    cursor: pointer;
    transition: all 0.3s ease;
    position: relative;
    overflow: hidden;
    box-sizing: border-box;
}

.calendar-cell:hover {
    background-color: #f5f7fa;
}

.calendar-cell:hover .add-duty-btn {
    opacity: 1;
}

.day-header {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    position: relative;
    z-index: 2;
    height: 100%;
    padding: 8px;
}

.date-number {
    font-size: 16px;
    font-weight: 600;
    color: #303133;
    flex-shrink: 0;
}

.duty-names {
    flex: 1;
    display: flex;
    flex-direction: row;
    flex-wrap: wrap;
    gap: 4px;
    margin-left: 4px;
    max-height: calc(100% - 16px);
    overflow: hidden;
}

.add-duty-btn {
    opacity: 0;
    transition: opacity 0.3s ease;
    flex-shrink: 0;
}

.duty-name-tag {
    padding: 2px 6px;
    border-radius: 3px;
    font-size: 11px;
    color: white;
    cursor: pointer;
    transition: all 0.3s ease;
    border: 1px solid transparent;
    position: relative;
    z-index: 1;
    word-wrap: break-word;
    word-break: break-all;
    max-width: 100%;
    box-sizing: border-box;
    line-height: 1.2;
    text-align: center;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

.duty-name-tag:hover {
    transform: translateY(-1px);
    box-shadow: 0 2px 6px rgba(0, 0, 0, 0.2);
    z-index: 10;
}



.duty-name-tag.day {
    background-color: #67c23a;
    border-color: #85ce61;
}

.duty-name-tag.night {
    background-color: #e6a23c;
    border-color: #ebb563;
}

.duty-name-tag.rest {
    background-color: #909399;
    border-color: #a6a9ad;
}



.list-view {
    background: white;
    padding: 20px;
    box-sizing: border-box;
    height: calc(100% - 120px);
}

.list-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    padding-bottom: 20px;
    border-bottom: 1px solid #ebeef5;
}

.list-controls {
    display: flex;
    align-items: center;
}

.list-stats {
    display: flex;
    align-items: center;
}


.date-cell {
    text-align: center;
}

.date-main {
    font-weight: 600;
    color: #303133;
}

.date-weekday {
    font-size: 12px;
    color: #909399;
    margin-top: 4px;
}

.name-cell {
    display: flex;
    align-items: center;
    gap: 8px;
}

.no-notes {
    color: #c0c4cc;
    font-style: italic;
}

.duty-dialog .el-dialog__body {
    padding: 30px 20px;
}

.dialog-footer {
    text-align: right;
    padding-top: 20px;
    border-top: 1px solid #ebeef5;
}

/* 响应式设计 */
@media (max-width: 768px) {
    .header {
        flex-direction: column;
        gap: 20px;
    }

    .header-right {
        width: 100%;
        justify-content: space-between;
    }

    .calendar-header {
        flex-direction: column;
        gap: 15px;
    }

    .calendar-legend {
        justify-content: center;
    }



    .duty-name-tag {
        font-size: 10px;
        padding: 2px 4px;
    }
}
</style>